package com.meitianhui.convenitenbuy.http.interceptor;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.BuildConfig;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.MD5Utils;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 参数加密拦截器
 */
public class SignatureInterceptor implements Interceptor {

    private int mSecurityType = 0;  // 0：appToken   1:userToken

    public SignatureInterceptor(int securityType) {
        this.mSecurityType = securityType;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        String codeUrl = java.net.URLDecoder.decode(url, "utf-8");   //解码
        //获取参数列表
        String[] parts = codeUrl.split("\\?");
        //TreeMap里面的数据会按照key值自动升序排列
        TreeMap<String, String> param_map = new TreeMap<String, String>();
        //获取参数对
        String[] param_pairs = parts[1].split("&");
        for (String pair : param_pairs) {
            String[] param = pair.split("=");
            if (param.length != 2) {
                //没有value的参数不进行处理
                continue;
            }
            param_map.put(param[0], param[1]);
        }
        //重新拼接url
        HttpUrl.Builder httpUrlBuilder = request.url().newBuilder();
        String sign = signParam(param_map, mSecurityType);
        //添加参数
        httpUrlBuilder.addQueryParameter("sign", sign);
        Request.Builder requestBuilder = request.newBuilder();
        requestBuilder.url(httpUrlBuilder.build());
        request = requestBuilder.build();
        if (BuildConfig.DEBUG) {
            LogUtils.i("请求URL", java.net.URLDecoder.decode(request.url().toString(), "utf-8"));
        }
        return chain.proceed(request);
    }

    /**
     * 进行参数加密
     *
     * @param param_map
     * @param securityType 0：appToken   1:userToken
     */
    private String signParam(TreeMap<String, String> param_map, int securityType) {
        StringBuilder sign = new StringBuilder();
        Iterator it = param_map.keySet().iterator();
        //拼接参数
        while (it.hasNext()) {
            String key = it.next().toString();
            String value = param_map.get(key);
            sign.append(key);
            sign.append("=");
            sign.append(value);
            sign.append("&");
        }
        String signs;
        if (securityType == 0) {
            signs = sign.toString().substring(0, sign.length() - 1) + InfoProvider.getAppSecurityCode(App.getInstance());
        } else {
            signs = sign.toString().substring(0, sign.length() - 1) + InfoProvider.getUserToken(App.getInstance()).getSecurity_code();
        }
        return MD5Utils.MD5Encode(signs, "UTF-8");
    }

}
